<?php

namespace App\Http\Controllers\Data;

use App\Http\Controllers\Controller;
use App\Models\Product;
use Illuminate\Http\Request;
use Validator;

class ProductController extends Controller
{
    public function SampleProduct()
    {
        $re = Product::orderBy('time', 'desc')->paginate(8);
        $data = null;
        for ($i = 0; $i < sizeof($re); ++$i) {
            $data[$i]['cover_img'] = $re[$i]['cover_img'];
            $data[$i]['name'] = $re[$i]['name'];
            $data[$i]['brief'] = $re[$i]['brief'];
            $data[$i]['id'] = $re[$i]['id'];
            $data[$i]['SCategories'] = $re[$i]['SCategories'];
            $data[$i]['LCategories'] = $re[$i]['LCategories'];
        }
        $data = (['data' => $data, 'totalpage' => $re->lastPage()]);
        return json_encode($data);
    }

    public function ProductCategorie(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'SCategories' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 401);
        }
        $data = null;
        $re = Product::where('SCategories', $request->categories)->orderBy('time', 'desc')->paginate(8);
        if ($re) {
            for ($i = 0; $i < sizeof($re); ++$i) {
                $data[$i]['img'] = $re[$i]['img'];
                $data[$i]['title'] = $re[$i]['title'];
                $data[$i]['content'] = $re[$i]['content'];
                $data[$i]['id'] = $re[$i]['id'];
                $data[$i]['time'] = $re[$i]['time'];
                $data[$i]['categories'] = $re[$i]['categories'];
            }
            $data = (['data' => $data, 'totalpage' => $re->lastPage()]);

            return json_encode($data);
        } else {
            session()->flash('false', '查找失败，无此类别！');
            $data = ['success' => false, 'message' => '无此类别'];
        }
    }

    public function NextProductInCategorie(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required',
            'SCategories' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 401);
        }
        $data = Product::where('id', '>', $request->id)->where(['SCategories' => $request->SCategories])->first();

        return json_encode($data);
    }

    public function NextProduct(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 401);
        }
        $data = Product::where('id', '>', $request->id)->first();
        if (!!$data) {
            return json_encode($data);
        } else {
            $data = ['success' => false, 'message' => '已经是最后一个！'];
            return json_encode($data);
        }

    }

    public function CompleteProduct(Product $product)
    {
        return json_encode($product);
    }

    public function ProductInsert(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|max:10',
            'brief' => 'required',
            'SCategories' => 'required|max:20',
            'LCategories' => 'required|max:20',
            'cover_img' => 'required',
            'u_id' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 401);
        }

        $product = $request->all();
        unset($product['cover_img']);
        $product['time'] = date('Y-m-d h:i:s', time());
        $res = Product::create($product);

        $totalCoverImg = glob('./temp/' . $request->u_id . '/product/CoverImg' . '*');
        $CoverImgNumber = count($totalCoverImg);
        $CoverImg = $request->cover_img;
        if ($CoverImgNumber == 0) {
            $CoverImg = $request->cover_img;
        } else {
            $CoverImghandler = opendir('./temp/' . $request->u_id . '/product/CoverImg');
            while (($CoverImgname = readdir($CoverImghandler)) !== false) {
                if ($CoverImgname != '.' && $CoverImgname != '..') {
                    $temp = explode('.', $CoverImgname);
                    $extension = end($temp);
                    $picName = $res['id'] . '.' . $extension;
                    $CoverImg = './product/CoverImg/' . $picName;
                    if (!file_exists($CoverImg)) {
                        $counter_file = $CoverImg;
                        $fopen = fopen($counter_file, 'wb '); //新建文件命令
                        fclose($fopen);
                    }
                    copy('./temp/' . $request->u_id . '/product/CoverImg/' . 'cover_img' . '.' . $extension, $CoverImg);
                }
            }
        }

        // $totalConModeImg = glob('./temp/product/ConModeImg' . '*');
        // $ConModeImgNumber = count($totalConModeImg);
        // $ConModeImg = null;
        // if ($ConModeImgNumber == 0) {
        //     $ConModeImg = null;
        // } else {
        //     $ConModeImghandler = opendir('./temp/product/ConModeImg');
        //     while (($ConModeImgname = readdir($ConModeImghandler)) !== false) {
        //         if ($ConModeImgname != '.' && $ConModeImgname != '..') {
        //             $temp = explode('.', $ConModeImgname);
        //             $extension = end($temp);
        //             $picName = $res['id'] . '.' . $extension;
        //             $ConModeImg = './product/ConModeImg/' . $picName;
        //             if (!file_exists($ConModeImg)) {
        //                 $counter_file = $ConModeImg;
        //                 $fopen = fopen($counter_file, 'wb '); //新建文件命令
        //                 fclose($fopen);
        //             }
        //             copy('./temp/product/ConModeImg/' . 'ConMode_img' . '.' . $extension, $ConModeImg);
        //         }
        //     }
        // }

        // $totalDetailsImg = glob('./temp/product/DetailsImg' . '*');
        // $DetailsImgNumber = count($totalDetailsImg);
        // $DetailsImg = null;
        // if ($DetailsImgNumber == 0) {
        //     $DetailsImg = null;
        // } else {
        //     $DetailsImghandler = opendir('./temp/product/DetailsImg');
        //     while (($DetailsImgname = readdir($DetailsImghandler)) !== false) {
        //         if ($DetailsImgname != '.' && $DetailsImgname != '..') {
        //             $temp = explode('.', $DetailsImgname);
        //             $extension = end($temp);
        //             $picName = $res['id'] . '.' . $extension;
        //             $DetailsImg = './product/DetailsImg/' . $picName;
        //             if (!file_exists($DetailsImg)) {
        //                 $counter_file = $DetailsImg;
        //                 $fopen = fopen($counter_file, 'wb '); //新建文件命令
        //                 fclose($fopen);
        //             }
        //             copy('./temp/product/DetailsImg/' . 'details_img' . '.' . $extension, $DetailsImg);
        //         }
        //     }
        // }
        $imgs = null;
        if (file_exists('./temp/' . $request->u_id . '/product/imgs')) {
            $totalimgs = glob('./temp/' . $request->u_id . '/product/imgs/' . '*');
            $countimgs = count($totalimgs);

            if ($countimgs == 0) {
                $imgs = null;
            } else {
                $imgs = '{"imgs":[';
                $imgshandler = opendir('./temp/' . $request->u_id . '/product/imgs');
                $FileNumber = count($totalimgs);
                while (($imgname = readdir($imgshandler)) !== false) {
                    if ($imgname != '.' && $imgname != '..') {
                        $temp = explode('.', $imgname);
                        $extension = end($temp);
                        $totalimgs = glob('./temp/' . $request->u_id . '/product/imgs/' . '*');
                        $picname = $res['id'] . '_' . $FileNumber . '.' . $extension;
                        $imgurl = './product/imgs/' . $picname;
                        if (!file_exists($imgurl)) {
                            $counter_file = $imgurl;
                            $fopen = fopen($counter_file, 'wb '); //新建文件命令
                            fclose($fopen);
                        }
                        --$FileNumber;
                        copy('./temp/' . $request->u_id . '/product/imgs/' . $imgname, $imgurl);
                        $imgs = $imgs . '{"imgname":"' . $imgname . '","url":"' . $imgurl . '"},';
                    }
                }
                $imgs = substr($imgs, 0, strlen($imgs) - 1);
                $imgs = $imgs . ']';
            }
        }

        $videos = null;
        if (file_exists('./temp/' . $request->u_id . '/product/videos')) {
            $totalvideos = glob('./temp/' . $request->u_id . '/product/videos/' . '*');
            $countvideos = count($totalvideos);

            if ($countvideos == 0) {
                $videos = null;
            } else {
                $videos = ',"video":[';
                $videoshandler = opendir('./temp/' . $request->u_id . '/product/videos');
                while (($videoname = readdir($videoshandler)) !== false) {
                    if ($videoname != '.' && $videoname != '..') {
                        $temp = explode('.', $videoname);
                        $extension = end($temp);

                        $picname = $res['id'] . '_' . $countvideos . '.' . $extension;
                        $videourl = './product/videos/' . $picname;

                        if (!file_exists($videourl)) {
                            $counter_file = $videourl;
                            $fopen = fopen($counter_file, 'wb '); //新建文件命令
                            fclose($fopen);
                        }
                        --$countvideos;
                        copy('./temp/' . $request->u_id . '/product/videos/' . $videoname, $videourl);
                        $videos = $videos . '{"videoname":"' . $videoname . '","url":"' . $videourl . '"},';
                    }
                }
                $videos = substr($videos, 0, strlen($videos) - 1);
            }
        }

        if ($imgs == null) {
            $imgs = null;
        } else {
            if ($videos == null) {
                $imgs = $imgs . '}';
            } else {
                $videos = $videos . ']}';
                $imgs = $imgs . $videos;
            }
        }

        $re = Product::where('id', $res['id'])
            ->update([
                'imgs' => $imgs,
                'cover_img' => $CoverImg,
                // 'details_img' => $DetailsImg,
                // 'ConMode_img' => $ConModeImg,
            ]);
        if (file_exists('./temp/' . $request->u_id . '/product/CoverImg')) {
            $dh = opendir('./temp/' . $request->u_id . '/product/CoverImg');
            while ($file = readdir($dh)) {
                if ($file != '.' && $file != '..') {
                    $fullpath = './temp/' . $request->u_id . '/product/CoverImg' . '/' . $file;
                    if (!is_dir($fullpath)) {
                        unlink($fullpath);
                    } else {
                        deldir($fullpath);
                    }
                }
            }
            closedir($dh);
        }
        if (file_exists('./temp/' . $request->u_id . '/product/imgs')) {
            $dh = opendir('./temp/' . $request->u_id . '/product/imgs');
            while ($file = readdir($dh)) {
                if ($file != '.' && $file != '..') {
                    $fullpath = './temp/' . $request->u_id . '/product/imgs' . '/' . $file;
                    if (!is_dir($fullpath)) {
                        unlink($fullpath);
                    } else {
                        deldir($fullpath);
                    }
                }
            }
            closedir($dh);
        }
        // if (file_exists('./temp/product/DetailsImg')) {
        //     $dh = opendir('./temp/product/DetailsImg');
        //     while ($file = readdir($dh)) {
        //         if ($file != '.' && $file != '..') {
        //             $fullpath = './temp/product/DetailsImg' . '/' . $file;
        //             if (!is_dir($fullpath)) {
        //                 unlink($fullpath);
        //             } else {
        //                 deldir($fullpath);
        //             }
        //         }
        //     }
        //     closedir($dh);
        // }
        // if (file_exists('./temp/product/ConModeImg')) {
        //     $dh = opendir('./temp/product/ConModeImg');
        //     while ($file = readdir($dh)) {
        //         if ($file != '.' && $file != '..') {
        //             $fullpath = './temp/product/ConModeImg' . '/' . $file;
        //             if (!is_dir($fullpath)) {
        //                 unlink($fullpath);
        //             } else {
        //                 deldir($fullpath);
        //             }
        //         }
        //     }
        //     closedir($dh);
        // }
        if (file_exists('./temp/' . $request->u_id . '/product/videos')) {
            $dh = opendir('./temp/' . $request->u_id . '/product/videos');
            while ($file = readdir($dh)) {
                if ($file != '.' && $file != '..') {
                    $fullpath = './temp/' . $request->u_id . '/product/videos' . '/' . $file;
                    if (!is_dir($fullpath)) {
                        unlink($fullpath);
                    } else {
                        deldir($fullpath);
                    }
                }
            }
            closedir($dh);
        }
        if ($re) {
            session()->flash('true', '新增成功！');
            $data = ['success' => true, 'message' => '新增成功'];

            return json_encode($data);
        } else {
            Product::destroy($res['id']);
            session()->flash('false', '新增失败,产品重复新增!');

            return redirect()->back();
        }
    }

    public function ProductUpdate(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|max:20',
            'brief' => 'required',
            'SCategories' => 'required|max:20',
            'LCategories' => 'required|max:20',
            'id' => 'required',
            'u_id' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 401);
        }
        $product = $request->all();
        unset($product['u_id']);
        $cover_del = Product::where('id', '=', $request->id)->first();
        if (isset($request->cover_img)) {
            if (file_exists($cover_del['cover_img'])) {
                unlink($cover_del['cover_img']);
            }
        }
        $totalCoverImg = glob('./temp/' . $request->u_id . '/product/CoverImg' . '*');
        $CoverImgNumber = count($totalCoverImg);
        if ($CoverImgNumber != 0) {
            $CoverImghandler = opendir('./temp/' . $request->u_id . '/product/CoverImg');
            while (($CoverImgname = readdir($CoverImghandler)) !== false) {
                if ($CoverImgname != '.' && $CoverImgname != '..') {
                    $temp = explode('.', $CoverImgname);
                    $extension = end($temp);
                    $picName = $request->id . '.' . $extension;
                    $CoverImg = './product/CoverImg/' . $picName;
                    if (!file_exists($CoverImg)) {
                        $counter_file = $CoverImg;
                        $fopen = fopen($counter_file, 'wb '); //新建文件命令
                        fclose($fopen);
                    }
                    copy('./temp/' . $request->u_id . '/product/CoverImg/' . 'cover_img' . '.' . $extension, $CoverImg);
                    $product['cover_img'] = $CoverImg;
                }
            }
        }

        // $totalConModeImg = glob('./temp/product/ConModeImg' . '*');
        // $ConModeImgNumber = count($totalConModeImg);
        // $ConModeImg = null;
        // if ($ConModeImgNumber == 0) {
        //     $ConModeImg = null;
        // } else {
        //     $ConModeImghandler = opendir('./temp/product/ConModeImg');
        //     while (($ConModeImgname = readdir($ConModeImghandler)) !== false) {
        //         if ($ConModeImgname != '.' && $ConModeImgname != '..') {
        //             $temp = explode('.', $ConModeImgname);
        //             $extension = end($temp);
        //             $picName = $request->id . '.' . $extension;
        //             $ConModeImg = './product/ConModeImg/' . $picName;
        //             if (!file_exists($ConModeImg)) {
        //                 $counter_file = $ConModeImg;

        //                 $fopen = fopen($counter_file, 'wb '); //新建文件命令
        //                 fclose($fopen);
        //             }
        //             copy('./temp/product/ConModeImg/' . 'ConMode_img' . '.' . $extension, $ConModeImg);
        //         }
        //     }
        // }

        // $totalDetailsImg = glob('./temp/product/DetailsImg' . '*');
        // $DetailsImgNumber = count($totalDetailsImg);
        // $DetailsImg = null;
        // if ($DetailsImgNumber == 0) {
        //     $DetailsImg = null;
        // } else {
        //     $DetailsImghandler = opendir('./temp/product/DetailsImg');
        //     while (($DetailsImgname = readdir($DetailsImghandler)) !== false) {
        //         if ($DetailsImgname != '.' && $DetailsImgname != '..') {
        //             $temp = explode('.', $DetailsImgname);
        //             $extension = end($temp);
        //             $picName = $request->id . '.' . $extension;
        //             $DetailsImg = './product/DetailsImg/' . $picName;
        //             if (!file_exists($DetailsImg)) {
        //                 $counter_file = $DetailsImg;

        //                 $fopen = fopen($counter_file, 'wb '); //新建文件命令
        //                 fclose($fopen);
        //             }
        //             copy('./temp/product/DetailsImg/' . 'details_img' . '.' . $extension, $DetailsImg);
        //         }
        //     }
        // }
        $res = Product::where('id', '=', $request->id)->first();
        if (isset($request->imgs)) {
            // echo 2;
            // exit;
            if (isset($res['imgs'])) {
                $imgs = json_decode($res['imgs']);
                if (isset($imgs->imgs)) {
                    for ($i = 0; $i < sizeof($imgs->imgs); ++$i) {
                        if (file_exists($imgs->imgs[$i]->url)) {
                            unlink($imgs->imgs[$i]->url);
                        }
                    }
                }

                if (isset($imgs->videos)) {
                    for ($i = 0; $i < sizeof($imgs->videos); ++$i) {
                        if (file_exists($imgs->videos[$i]->url)) {
                            unlink($imgs->videos[$i]->url);
                        }
                    }
                }
            }
        }
        $imgs = null;
        if (file_exists('./temp/' . $request->u_id . '/product/imgs/')) {
            $totalimgs = glob('./temp/' . $request->u_id . '/product/imgs/' . '*');
            $countimgs = count($totalimgs);

            if ($countimgs == 0) {
                $imgs = null;
            } else {
                $imgs = '{"imgs":[';
                $imgshandler = opendir('./temp/' . $request->u_id . '/product/imgs');
                $FileNumber = count($totalimgs);
                while (($imgname = readdir($imgshandler)) !== false) {
                    if ($imgname != '.' && $imgname != '..') {
                        $temp = explode('.', $imgname);
                        $extension = end($temp);
                        $totalimgs = glob('./temp/' . $request->u_id . '/product/imgs/' . '*');
                        $picname = $request->id . '_' . $FileNumber . '.' . $extension;
                        $imgurl = './product/imgs/' . $picname;
                        if (!file_exists($imgurl)) {
                            $counter_file = $imgurl;
                            $fopen = fopen($counter_file, 'wb '); //新建文件命令
                            fclose($fopen);
                        }
                        --$FileNumber;
                        copy('./temp/' . $request->u_id . '/product/imgs/' . $imgname, $imgurl);
                        $imgs = $imgs . '{"imgname":"' . $imgname . '","url":"' . $imgurl . '"},';
                    }
                }
                $imgs = substr($imgs, 0, strlen($imgs) - 1);
                $imgs = $imgs . ']';
            }
        }
        $videos = null;
        if (file_exists('./temp/' . $request->u_id . '/product/imgs/')) {
            $totalvideos = glob('./temp/' . $request->u_id . '/product/videos/' . '*');
            $countvideos = count($totalvideos);
            $videos = ',"video":[';
            if ($countvideos == 0) {
                $videos = null;
            } else {
                $videoshandler = opendir('./temp/' . $request->u_id . '/product/videos');
                while (($videoname = readdir($videoshandler)) !== false) {
                    if ($videoname != '.' && $videoname != '..') {
                        $temp = explode('.', $videoname);
                        $extension = end($temp);

                        $picname = $request->id . '_' . $countvideos . '.' . $extension;
                        $videourl = './product/videos/' . $picname;

                        if (!file_exists($videourl)) {
                            $counter_file = $videourl;
                            $fopen = fopen($counter_file, 'wb '); //新建文件命令
                            fclose($fopen);
                        }
                        --$countvideos;
                        copy('./temp/' . $request->u_id . '/product/videos/' . $videoname, $videourl);
                        $videos = $videos . '{"videoname":"' . $videoname . '","url":"' . $videourl . '"},';
                    }
                }
                $videos = substr($videos, 0, strlen($videos) - 1);
            }
        }
        if ($countimgs == 0) {
            $imgs = null;
        } else {
            if ($countvideos == 0) {
                $imgs = $imgs . '}';
            } else {
                $videos = $videos . ']}';
                $imgs = $imgs . $videos;
            }
        }

        $product['imgs'] = $imgs;
        // $product['ConMode_img'] = $ConModeImg;
        // $product['details_img'] = $DetailsImg;
        unset($product['id']);
        $original = Product::where('id', '=', $request->id)->first();
        unset($original['id']);
        if ($original == $product) {
            $data = ['success' => false, 'message' => '修改的内容与原先内容相同！'];

            return json_encode($data);
        }

        $re = Product::where('id', $request->id)->update($product);
        if (file_exists('./temp/' . $request->u_id . '/product/CoverImg')) {
            $dh = opendir('./temp/' . $request->u_id . '/product/CoverImg');
            while ($file = readdir($dh)) {
                if ($file != '.' && $file != '..') {
                    $fullpath = './temp/' . $request->u_id . '/product/CoverImg' . '/' . $file;
                    if (!is_dir($fullpath)) {
                        unlink($fullpath);
                    } else {
                        deldir($fullpath);
                    }
                }
            }
            closedir($dh);
        }
        if (file_exists('./temp/' . $request->u_id . '/product/imgs')) {
            $dh = opendir('./temp/' . $request->u_id . '/product/imgs');
            while ($file = readdir($dh)) {
                if ($file != '.' && $file != '..') {
                    $fullpath = './temp/' . $request->u_id . '/product/imgs' . '/' . $file;
                    if (!is_dir($fullpath)) {
                        unlink($fullpath);
                    } else {
                        deldir($fullpath);
                    }
                }
            }
            closedir($dh);
        }
        if (file_exists('./temp/' . $request->u_id . '/product/Videos')) {
            $dh = opendir('./temp/' . $request->u_id . '/product/Videos');
            while ($file = readdir($dh)) {
                if ($file != '.' && $file != '..') {
                    $fullpath = './temp/' . $request->u_id . '/product/Videos' . '/' . $file;
                    if (!is_dir($fullpath)) {
                        unlink($fullpath);
                    } else {
                        deldir($fullpath);
                    }
                }
            }
            closedir($dh);
        }
        // if (file_exists('./temp/product/DetailsImg')) {
        //     $dh = opendir('./temp/product/DetailsImg');
        //     while ($file = readdir($dh)) {
        //         if ($file != '.' && $file != '..') {
        //             $fullpath = './temp/product/DetailsImg' . '/' . $file;
        //             if (!is_dir($fullpath)) {
        //                 unlink($fullpath);
        //             } else {
        //                 deldir($fullpath);
        //             }
        //         }
        //     }
        //     closedir($dh);
        // }
        // if (file_exists('./temp/product/ConModeImg')) {
        //     $dh = opendir('./temp/product/ConModeImg');
        //     while ($file = readdir($dh)) {
        //         if ($file != '.' && $file != '..') {
        //             $fullpath = './temp/product/ConModeImg' . '/' . $file;
        //             if (!is_dir($fullpath)) {
        //                 unlink($fullpath);
        //             } else {
        //                 deldir($fullpath);
        //             }
        //         }
        //     }
        //     closedir($dh);
        // }
        if ($re) {
            session()->flash('true', '修改成功！');
            $data = ['success' => true, 'message' => '修改成功'];

            return json_encode($data);
        } else {
            session()->flash('false', '修改失败,无对应id!');

            return redirect()->back();
        }
    }

    public function ProductDelete(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 401);
        }
        $res = Product::where('id', '=', $request->id)->first();
        $re = Product::where('id', '=', $request->id)->delete();
        if ($re) {
            if ((isset($res['cover_img']))) {
                if (file_exists($res['cover_img'])) {
                    unlink($res['cover_img']);
                }
            }
            // if (isset($res['details_img'])) {
            //     if (file_exists($res['details_img'])) {
            //         unlink($res['details_img']);
            //     }
            // }
            // if (isset($res['ConMode_img'])) {
            //     if (file_exists($res['ConMode_img'])) {
            //         unlink($res['ConMode_img']);
            //     }
            // }
            if (isset($res['imgs'])) {
                $imgs = json_decode($res['imgs']);

                if (isset($imgs->imgs)) {
                    for ($i = 0; $i < sizeof($imgs->imgs); ++$i) {
                        if (file_exists($imgs->imgs[$i]->url)) {
                            unlink($imgs->imgs[$i]->url);
                        }
                    }
                }

                if (isset($imgs->videos)) {
                    for ($i = 0; $i < sizeof($imgs->videos); ++$i) {
                        if (file_exists($imgs->videos[$i]->url)) {
                            unlink($imgs->videos[$i]->url);
                        }
                    }
                }
            }
            session()->flash('true', '删除成功！');
            $data = ['success' => true, 'message' => '删除成功'];

            return json_encode($data);
        } else {
            session()->flash('false', '删除失败，无对应ID信息!');

            return redirect()->back();
        }
    }
}
